package com.creating.mict.common;

//先加入dom4j.jar包 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.creating.mict.common.db.OperOrcl;
import com.creating.mict.common.mess.SMSCaClient;

/**
 * 
 * @ClassName: Dom4j
 * @Description: 解析xml字符串
 * @author xuelei
 * @date Feb 5, 2013 9:28:15 PM
 * 
 */
public class Dom4j {

	private static Logger logger = Logger.getLogger(Dom4j.class);

	/**
	 * 
	 * @Title: readStringXmlAndSaveObj
	 * @Description: 解析LIS结果XML并存入数据库
	 * @param
	 * @param xml
	 * @return void 返回类型
	 * @throws
	 */
	public static void readLisXmlAndSave(String xml) {
		Document doc = null;
		try {
			
			String mrn = "";
			String universalPid = "";
			String cellPhoneNumber = "";
			String provider = "";
			String timeCompleted = "";
			String examName = "";
			String examValue = "";
			String referValue = "";
			String examResult = "";

			String sql = "";

			// 下面的是通过解析xml字符串的
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点

			mrn = rootElt.elementTextTrim("mrn");
			universalPid = rootElt.elementTextTrim("universalPid");
			cellPhoneNumber = "";
			provider = rootElt.elementTextTrim("cellPhoneNumber");
			timeCompleted = rootElt.elementTextTrim("timeCompleted");

			OperOrcl operOrcl = new OperOrcl();
			DateUtils dateUtils = new DateUtils();
			int forder = 0;

			Iterator iter = rootElt.elementIterator("lisExams"); // 获取根节点下的子节点head
			// 遍历head节点
			while (iter.hasNext()) {
				Element recordEle = (Element) iter.next();
				Iterator iters = recordEle.elementIterator("lisExam"); // 获取子节点head下的子节点script
				// 遍历Header节点下的Response节点
				while (iters.hasNext()) {
					forder++; // 序号

					Element itemEle = (Element) iters.next();
					examName = itemEle.elementTextTrim("examName"); // 拿到head下的子节点script下的字节点username的值
					examValue = itemEle.elementTextTrim("examValue");
					examResult = itemEle.elementTextTrim("examResult");
					referValue = itemEle.elementTextTrim("referValue"); // 拿到head下的子节点script下的字节点username的值

					sql = "insert into TDS_LIS_RECORD(fid, fpatientid, fdate, fdesc, fvalue, freference, fsuggest, fdoc, fflag, forder) "
							+ " values('"
							+ dateUtils.getTransactionIdByLongTime()
							+ "',"
							+ " '"
							+ universalPid
							+ "', "

							+ " to_date('"
							+ timeCompleted.trim()
							+ "','yyyy-mm-dd'), "
							+ " '"
							+ examName
							+ "', "
							+ " '"
							+ examValue
							+ "', "
							+ " '"
							+ referValue
							+ "', "
							+ " '"
							+ examResult
							+ "', "
							+ " '"
							+ provider
							+ "', "
							+ " '0', "
							+ " '"
							+ forder
							+ "')";

					// System.out.println("sql====：" + sql);
					// 保存检查结果
					operOrcl.getUpdate(sql);
					logger.info("保存LIS检查结果：" + sql);
				}
			}

		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: readXyjReceiveMessXml
	 * @Description: 获取血压计信息并存入数据库
	 * @param
	 * @param xml
	 * @return void 返回类型
	 * @throws
	 */
	public static void readXyjReceiveMessXmlAndSave(String xml) {
		Document doc = null;
		try {
			saveMessageReceived(xml);
			
			OperOrcl operOrcl = new OperOrcl();
			DateUtils dateUtils = new DateUtils();
			String numberuser = "";
            String msgcontent = "";
            String msgtime = "";
			String fssy = "";
			String fszy = "";
			String fxl = "";
			String fcqxt = ""; //餐前血糖
			String fchxt1 = ""; // 餐后一小时血糖
			String fchxt2 = ""; //餐后两小时血糖

			String sql = "";

			// 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Iterator iter = rootElt.elementIterator("Body"); // 获取根节点下的子节点head
            // 遍历head节点
                Element recordEle = (Element) iter.next();
                System.out.println("节点1：" + recordEle.getName());
                Iterator iters = recordEle.elementIterator("recvmoResponse"); // 获取子节点head下的子节点script
                Element recordEle2 = (Element) iters.next();
                System.out.println("节点2：" + recordEle2.getName());
                
                Iterator iters3 = recordEle2.elementIterator("sms"); // 获取子节点head下的子节点script
                Element recordEle3 = (Element) iters3.next();
                System.out.println("节点3：" + recordEle3.getName());
                
                Iterator iters4 = recordEle3.elementIterator("msg"); // 获取子节点head下的子节点script
//                Element recordEle4 = (Element) iters4.next();
//                System.out.println("节点4：" + recordEle4.getName());

                // 遍历Header节点下的Response节点
                while (iters4.hasNext()) {
                	fcqxt = "";
                	fchxt1 = "";
                	fchxt2 = "";
                	msgtime = "";
                	
                	fssy = "";
                	fszy = "";
                	fxl = "";
                	
                    Element itemEle = (Element) iters4.next();
                    numberuser = itemEle.elementTextTrim("numberuser"); // 拿到head下的子节点script下的字节点username的值
                    msgcontent = itemEle.elementTextTrim("msgcontent");
                    msgtime = itemEle.elementTextTrim("msgtime");
                    msgcontent = msgcontent.trim();
                    System.out.println("msgcontent----------------：-----------------" + msgcontent);
                    if(msgcontent.startsWith("01.") || msgcontent.startsWith("02.") || msgcontent.startsWith("03.")) {
//                    	msgcontent = "01.餐前空腹血糖测试结果：血糖浓度：9.2mmol/L 12-13";
//                    	msgcontent = "02.餐后一小时血糖测试结果:血糖浓度：8.9mmol/L08-3506-01-2013";
                    	String str_t = ""; 
                		
                    	//判断血糖类别
                    	if(msgcontent.startsWith("01.")) {
                    		String str[] = msgcontent.split("：");
                    		if(str[1] != null) {
                    			str_t = str[1];
                    			String xtnd[] = str_t.split("mmol");
                    			fcqxt = xtnd[0];
                            } else {
                            	fcqxt = "";
                            }
//                    		System.out.println("------------------" + fcqxt);
                    	}
                    	if(msgcontent.startsWith("02.")) {
                    		String str[] = msgcontent.split(":");
                    		if(str[1] != null) {
                    			str_t = str[1];
                    			String xtnd[] = str_t.split("mmol");
                    			fchxt1 = xtnd[0];
                            } else {
                            	fchxt1 = "";
                            }
                    	}
                    	if(msgcontent.startsWith("03.")) {
                    		String str[] = msgcontent.split(":");
                    		if(str[1] != null) {
                    			str_t = str[1];
                    			String xtnd[] = str_t.split("mmol");
                    			fchxt2 = xtnd[0];
                            } else {
                            	fchxt2 = "";
                            }
                    	}
                    	
                    	fcqxt = fcqxt.replace("血糖浓度：", "");
                    	fchxt1 = fchxt1.replace("血糖浓度：", "");
                    	fchxt2 = fchxt2.replace("血糖浓度：", "");
                    	
                    	sql = "insert into TDS_XTY_RECORD(fid, fphone, fcqxt, fchxt1, fchxt2, frdate) "
							+ " values('"
							+ dateUtils.getTransactionIdByLongTime()
							+ "',"
							+ " '"
							+ numberuser
							+ "', "
							+ " '"
							+ fcqxt
							+ "', "
							+ " '"
							+ fchxt1
							+ "', "	
							+ " '"
							+ fchxt2
							+ "', "
							
							+ " to_date('"
							+ msgtime
							+ "','YYYY-MM-DD HH24:MI:SS') "
							+ ")";
					
					logger.info("血糖SQL------" + sql);
					// 保存监测结果短信
					operOrcl.getUpdate(sql);
                    	
                    } else {
                    	msgcontent = msgcontent.replace("高压：", ",");
                        msgcontent = msgcontent.replace("低压：", ",");
                        msgcontent = msgcontent.replace("脉率：", ",");
                        msgcontent = msgcontent.replace("mmHg", "");
                        msgcontent = msgcontent.replace("min", ",");
                    
//                    msgcontent = msgcontent.replace("高压：", ",");
//                    msgcontent = msgcontent.replace("低压：", ",");
//                    msgcontent = msgcontent.replace("脉率：", ",");
//                    msgcontent = msgcontent.replace("mmHg", "");
//                    msgcontent = msgcontent.replace("min", ",");
//                    System.out.println("节点4：" + msgcontent);
                    String str[] = msgcontent.split(",");
                    
                    if(str[1] != null) {
                    	fssy = str[1];
                    }
                    if(str[2] != null) {
                    	fszy = str[2];
                    }
                    if(str[3] != null) {
                    	fxl = str[3];
                    }
                    
//                    
					sql = "insert into TDS_XYJ_RECORD(fid, fphone, fssy, fszy, fxl, frdate) "
							+ " values('"
							+ dateUtils.getTransactionIdByLongTime()
							+ "',"
							+ " '"
							+ numberuser
							+ "', "
							+ " '"
							+ fssy
							+ "', "
							+ " '"
							+ fszy
							+ "', "	
							+ " '"
							+ fxl
							+ "', "
							
							+ " to_date('"
							+ msgtime
							+ "','YYYY-MM-DD HH24:MI:SS') "
							+ ")";

					logger.info("血压SQL------" + sql);
					// 保存监测结果短信
					operOrcl.getUpdate(sql);
					
                    }
				}

		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public static void readStringXml(String xml) {

        Document doc = null;

        try {
        	
        	saveMessageReceived(xml);
            // 读取并解析XML文档
            // SAXReader就是一个管道，用一个流的方式，把xml文件读出来
            // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档
            // Document document = reader.read(new File("User.hbm.xml"));
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Iterator iter = rootElt.elementIterator("Body"); // 获取根节点下的子节点head
            // 遍历head节点
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                System.out.println("节点1：" + recordEle.getName());
                Iterator iters = recordEle.elementIterator("recvmoResponse"); // 获取子节点head下的子节点script
                Element recordEle2 = (Element) iters.next();
                System.out.println("节点2：" + recordEle2.getName());
                
                Iterator iters3 = recordEle2.elementIterator("sms"); // 获取子节点head下的子节点script
                Element recordEle3 = (Element) iters3.next();
                System.out.println("节点3：" + recordEle3.getName());
                
                Iterator iters4 = recordEle3.elementIterator("msg"); // 获取子节点head下的子节点script
//                Element recordEle4 = (Element) iters4.next();
//                System.out.println("节点4：" + recordEle4.getName());

                // 遍历Header节点下的Response节点
                while (iters4.hasNext()) {
                    Element itemEle = (Element) iters4.next();
                    String numberuser = itemEle.elementTextTrim("numberuser"); // 拿到head下的子节点script下的字节点username的值
                    String msgcontent = itemEle.elementTextTrim("msgcontent");
                    String msgtime = itemEle.elementTextTrim("msgtime");
                
                    msgcontent = msgcontent.replace("高压：", "$$");
                    msgcontent = msgcontent.replace("低压：", "$$");
                    msgcontent = msgcontent.replace("脉率：", "$$");
                    msgcontent = msgcontent.replace("mmHg", "");
                    msgcontent = msgcontent.replace("min", "$$");
                  
                    System.out.println("最后内容：" + msgcontent);
                }
            }
            Iterator iterss = rootElt.elementIterator("body"); ///获取根节点下的子节点body
            // 遍历body节点
            while (iterss.hasNext()) {
                Element recordEless = (Element) iterss.next();
                String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
                System.out.println("result:" + result);
                Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
                // 遍历Header节点下的Response节点
                while (itersElIterator.hasNext()) {
                    Element itemEle = (Element) itersElIterator.next();
                    String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
                    String subID = itemEle.elementTextTrim("subID");
                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
	
	/**
	 * 
	* @Title: saveMessageReceived 
	* @Description: 保存接收到的信息至文本
	* @param @param str 
	* @return void    返回类型 
	* @throws
	 */
	public static void saveMessageReceived(String str) {
		DateUtils dateUtils = new DateUtils();
		FileWriter writer;
		try {
			writer = new FileWriter("E:\\receivedmess\\mess_" + dateUtils.getTransactionIdByTime() + ".txt");
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 


	

//	public static void main(String[] args) {
		
		
//		
//		String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
//			+ "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" > "
//			+ "<soap:Body> "
//			+ "<recvmoResponse xmlns=\"http://cpsms.org.cn/\"> "
//			+ "<sms xmlns=\"http://respmo.cpsms.org.cn/\"> "
//			+ "<result>0</result> "
//			+ "<errorinfo>OK</errorinfo> "
//			+ "<recvnum>4</recvnum> "
//			+ "<msg> "
//			+ "<itemid>105</itemid> "
//			+ "<momsgid /> "
//			+ "<numberuser>15105210211</numberuser> "
//			+ "<numbersub>3</numbersub> "
//			+ "<msgcontent>高压：160mmHg低压：96mmHg脉率：63min10-0401-06-2012</msgcontent>"
//			+ "<msgtype>4</msgtype> "
//			+ "<msgtime>2013-02-20 14:28:35</msgtime> "
//			+ "<reserve /> "
//			+ "</msg> "
//			
//			+ "<msg> "
//			+ "<itemid>105</itemid> "
//			+ "<momsgid /> "
//			+ "<numberuser>15105210213</numberuser> "
//			+ "<numbersub>3</numbersub> "
//			+ "<msgcontent>高压：160mmHg低压：96mmHg脉率：63min10-0401-06-2012</msgcontent>"
//			+ "<msgtype>4</msgtype> "
//			+ "<msgtime>2013-02-20 14:28:35</msgtime> "
//			+ "<reserve /> "
//			+ "</msg> "
//			
//			+ "<msg> "
//			+ "<itemid>105</itemid> "
//			+ "<momsgid /> "
//			+ "<numberuser>15105210212</numberuser> "
//			+ "<numbersub>3</numbersub> "
//			+ "<msgcontent>高压：160mmHg低压：96mmHg脉率：63min10-0401-06-2012</msgcontent>"
//			+ "<msgtype>4</msgtype> "
//			+ "<msgtime>2013-02-20 14:28:35</msgtime> "
//			+ "<reserve /> "
//			+ "</msg> "
//			
//			+ "</sms> "
//			+ "</recvmoResponse> "
//			+ "</soap:Body> "
//			+ "</soap:Envelope> ";
//
//		System.out.println("----------" + xmlStr.startsWith("<?xml"));
		
		
		
		
//		String xmlStr = "<AddLisExamRequest> "
//				+ "<mrn>212100910008</mrn> "
//				+ "<universalPid>bfab8ed3-69c0-4fed-8e4d-259c90b03b3e</universalPid> "
//				+ "<cellPhoneNumber>13621268002</cellPhoneNumber> "
//				+ "<specimen>血</specimen> " + "<specimenNo>1</specimenNo> "
//				+ "<provider>赵慧</provider> " + "<authority /> "
//				+ "<timeCompleted>2012-10-09</timeCompleted> " + "<remarks /> "
//				+ "<lisExams> " + "<lisExam> " + "<examName>白细胞</examName> "
//				+ "<examValue>7.50</examValue> "
//				+ "<examUnit>10~9|/L</examUnit> "
//				+ "<examResult></examResult> "
//				+ "<referValue>4-10</referValue> " + "</lisExam> "
//				+ "<lisExam> " + "<examName>淋巴细胞数</examName> "
//				+ "<examValue>1.1</examValue> "
//				+ "<examUnit>10~9|/L</examUnit> "
//				+ "<examResult></examResult> "
//				+ "<referValue>0.8-4.0</referValue> " + "</lisExam> "
//				+ "<lisExam> " + "<examName>中间细胞数目</examName> "
//				+ "<examValue>0.4</examValue> "
//				+ "<examUnit>10~9|/L</examUnit> "
//				+ "<examResult></examResult> "
//				+ "<referValue>0.1-0.9</referValue> " + "</lisExam> "
//				+ "</lisExams> " + "<sourcePatientID> "
//				+ "20070702022^^^&amp;amp;0210&amp;amp;ISO "
//				+ "</sourcePatientID> " + "</AddLisExamRequest>";
//
//		readLisXmlAndSave(xmlStr);
		
//		readXyjReceiveMessXmlAndSave(SMSCaClient.testPost(SMSCaClient.receiveMessXmlInfo()));
		
//	}

}